package com.atguigu.yygh.order.controller;

import com.atguigu.yygh.enums.OrderStatusEnum;
import com.atguigu.yygh.enums.PaymentStatusEnum;
import com.atguigu.yygh.exception.YYGHException;
import com.atguigu.yygh.model.order.OrderInfo;
import com.atguigu.yygh.model.order.PaymentInfo;
import com.atguigu.yygh.order.service.OrderInfoService;
import com.atguigu.yygh.order.service.PaymentService;
import com.atguigu.yygh.order.service.WeiPayService;
import com.atguigu.yygh.result.R;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.Map;

/*==========================================
      时 间:   2022-04-28
      讲 师:   刘  辉
      描 述:   尚硅谷教学团队
 ==========================================*/
@RestController
@RequestMapping("/api/orderInfo/weixin")
public class WeiPayController {

    @Autowired
    private WeiPayService weiPayService;

    @Autowired
    private OrderInfoService orderInfoService;
    @Autowired
    private PaymentService paymentService;


    @GetMapping("/status/{orderId}")
    public R getOrderStatus(@PathVariable Long orderId){
       Map<String,String> map= weiPayService.getOrderStatus(orderId);
       if(map== null){
           throw new YYGHException(20001,"支付失败");
       }
       //
        if("SUCCESS".equals(map.get("trade_state"))){
            //付款成功：更新订单的状态和支付记录表中的支付支付状态
            OrderInfo orderInfo=new OrderInfo();
            orderInfo.setId(orderId);
            orderInfo.setOrderStatus(OrderStatusEnum.PAID.getStatus());
            orderInfoService.updateById(orderInfo);

            UpdateWrapper<PaymentInfo> updateWrapper=new UpdateWrapper<PaymentInfo>();
            updateWrapper.eq("order_id",orderId);
            updateWrapper.set("payment_status", PaymentStatusEnum.PAID.getStatus());
            updateWrapper.set("callback_time",new Date());
            updateWrapper.set("callback_content",map.toString());
            updateWrapper.set("trade_no",map.get("transaction_id"));
            paymentService.update(updateWrapper);

            return R.ok();
        }
        return R.ok().message("支付中");
    }

    @GetMapping("/createNative/{orderId}")
    public R createNative(@PathVariable Long orderId){
        String url= weiPayService.createNative(orderId);
        return R.ok().data("url",url);
    }
}
